'use strict'
import { Sequelize } from 'sequelize'
import path from 'path'
import fs from 'fs'
import configData from '@/config/sequelize'
import { Models } from '../type'

const env = (process.env.NODE_ENV as Env) || 'development'
const config = configData[env] as any
// const config = require(__dirname + '/config.json')[env]
const sequelize: Sequelize = config.url
  ? new Sequelize(config.url as string, config)
  : new Sequelize(config.database, config.username, config.password, config)

const basename = path.basename(__filename)

const db: Models = {}

fs.readdirSync(__dirname)
  .filter((file) => {
    return (
      file.indexOf('.') !== 0 &&
      file !== basename &&
      ['.js', '.ts'].includes(file.slice(-3)) &&
      file.indexOf('.test.') === -1
    )
  })
  .forEach(async (file) => {
    try {
      const module = await import(path.join(__dirname, file))
      const model = module.default
      if (model.associate && typeof model.associate === 'function') {
        model.associate(sequelize.models)
      }
      // db[model.name] = model
    } catch (error) {
      console.error('导入失败：', error)
    }
  })

export default sequelize
